import com.suxii.pojo.ChatMsg;
import com.suxii.pojo.LoginMsg;
import com.suxii.procotol.ChatCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.channel(NioSocketChannel.class);
            b.group(group);
            b.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChatCodec()); //添加编解码器
                    ch.pipeline().addLast(new ChannelOutboundHandlerAdapter(){
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                            String[] s = msg.toString().split(" ");
                            //super.write(ctx, new ChatMsg(s[0],Integer.parseInt(s[1]), s[2]), promise);

                            //super.write(ctx, new LoginMsg(Integer.parseInt(s[0]),s[1]), promise);
                            super.write(ctx, new ChatMsg("xiaoming",222,s[1],Integer.parseInt(s[0])), promise);
                            //super.write(ctx, new ChatMsg("tom",123,s[1],Integer.parseInt(s[0])), promise);
                        }
                    });
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            super.channelRead(ctx, msg);
                            System.out.println(msg);
                        }
                    });

                }
            });
            ChannelFuture future = b.connect(new InetSocketAddress("127.0.0.1", 6666)).sync();
            Channel channel = future.channel();
            new Thread(()->{
                Scanner scanner=new Scanner(System.in);
                while (true){
                    String s = scanner.nextLine();
                    if (s.equals("q")){
                        channel.close();
                        break;
                    }
                    channel.writeAndFlush(s);
                }
            },"input").start();

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
